﻿using Bigger.Framework;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Bigger.Study.ConsoleApp.Async
{
    public class EAPAsyncExample : IExample
    {
        public void Execute()
        {
            BackgroundWorker objBackgroundWorker = new BackgroundWorker();
            objBackgroundWorker.DoWork += objBackgroundWorker_DoWork;
            objBackgroundWorker.WorkerSupportsCancellation = true;
            objBackgroundWorker.WorkerReportsProgress = true;
            objBackgroundWorker.ProgressChanged += objBackgroundWorker_ProgressChanged;
            objBackgroundWorker.RunWorkerCompleted += objBackgroundWorker_RunWorkerCompleted;

            ConsoleHelper.WriteLineYellow("BackgroundWorker是否正在运行异步操作：" + objBackgroundWorker.IsBusy);
            ConsoleHelper.WriteLineYellow("RunWorkerAsync代码行开始执行");
            objBackgroundWorker.RunWorkerAsync();
            ConsoleHelper.WriteLineYellow("RunWorkerAsync代码行结束执行");
            ConsoleHelper.WriteLineYellow("BackgroundWorker是否正在运行异步操作：" + objBackgroundWorker.IsBusy);

            Thread.Sleep(2000);
            ConsoleHelper.WriteLineYellow("CancelAsync代码行开始执行");
            objBackgroundWorker.CancelAsync();
            ConsoleHelper.WriteLineYellow("CancelAsync代码行开始执行");
        }

        void objBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker objBackgroundWorker = sender as BackgroundWorker;
            for (int i = 0; i < 10; i++)
            {
                //ConsoleHelper.WriteLineYellow("DoWork执行" + i);
                ConsoleHelper.WriteLineYellow("BackgroundWorker是否取消：" + objBackgroundWorker.CancellationPending);
                objBackgroundWorker.ReportProgress(i + 1, new Tuple<string>("Progress" + i));
                Thread.Sleep(500);
            }

            //while (objBackgroundWorker.IsBusy && !objBackgroundWorker.CancellationPending)
            //{
            //    //DoSomething
            //}
        }

        void objBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ConsoleHelper.WriteLineYellow(string.Format("BackgroundWorker执行进度：{0}%", e.ProgressPercentage * 100 / 10));
        }

        void objBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ConsoleHelper.WriteLineYellow("BackgroundWorker任务完成");
        }
    }
}
